package com.itheima.user.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.itheima.common.pojo.TbOrder;
import com.itheima.common.pojo.TbUser;
import com.itheima.common.response.OrderVo;
import com.itheima.common.response.UserOrderVo;
import com.itheima.user.feign.OrderFeign;
import com.itheima.user.mapper.UserMapper;
import com.itheima.user.service.UserService;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

/**
 * @作者 itcast
 * @创建日期 2020/10/11 15:59
 **/
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    UserMapper userMapper;
    @Autowired
    OrderFeign orderFeign;


    @Override
    public UserOrderVo findUserOrderVoByUsername(String username) throws Exception {
        // 1. 根据用户名 查询user信息
        TbUser tbUser = userMapper.selectOne(Wrappers.<TbUser>lambdaQuery().eq(TbUser::getUsername, username));
        // 2. 根据用户名 远程查询order服务中的订单信息
        List<TbOrder> orderList = orderFeign.findOrderByUsername(username);
        // 3. 封装UserOrderVo
        UserOrderVo userOrderVo = parseUserOrderVo(tbUser, orderList);
        return userOrderVo;
    }
    /**
     * 封装VO对象
     * @param tbUser
     * @param orderList
     * @return
     * @throws Exception
     */
    private UserOrderVo parseUserOrderVo(TbUser tbUser,List<TbOrder> orderList) throws Exception {
        UserOrderVo userOrderVo = new UserOrderVo();
        BeanUtils.copyProperties(userOrderVo,tbUser);
        List<OrderVo> orderVoList = new ArrayList<>();
        for (TbOrder tbOrder : orderList) {
            OrderVo orderVo = new OrderVo();
            BeanUtils.copyProperties(orderVo,tbOrder);

            orderVoList.add(orderVo);
        }
        userOrderVo.setTbOrders(orderVoList);
        return userOrderVo;
    }
}
